package com.lechuang.cunpinke.network;


import com.lechuang.cunpinke.BuildConfig;
import com.lechuang.cunpinke.network.converter.StringConverFactory;
import com.lechuang.cunpinke.network.converter.StringGsonConverFactory;
import com.lechuang.cunpinke.utils.LogUtils;

import java.io.IOException;
import java.net.Proxy;
import java.nio.charset.Charset;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;
import retrofit2.CallAdapter;
import retrofit2.Converter;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;

/**
 * 作者：尹松涛
 * 邮箱：yinsongtaoshmily@outlook.com
 * 日期：2017/9/26
 * 时间：11:02
 */

public class Netword {
    private static final Charset UTF8 = Charset.forName("UTF-8");
    private OkHttpClient okHttpClient;
    private static Converter.Factory stringConverteFactory = new StringConverFactory();
    private Converter.Factory stringGsonConverteFactory = StringGsonConverFactory.create();
    private CallAdapter.Factory rxJavaCallAdapterFactory = RxJavaCallAdapterFactory.create();
    private MyInterceptor interceptor;
    private static Netword instance;

    public static void init() {
        instance = new Netword();
    }

    public static Netword getInstance() {
        return instance;
    }

    public OkHttpClient getOkHttpClient() {
        if (okHttpClient == null) {
            interceptor = new MyInterceptor();
            if (BuildConfig.DEBUG) {
                okHttpClient = new OkHttpClient.Builder().addInterceptor(interceptor).readTimeout(50, TimeUnit.SECONDS).writeTimeout(50, TimeUnit.SECONDS).connectTimeout(15, TimeUnit.SECONDS).build();
            } else {
                okHttpClient = new OkHttpClient.Builder().proxy(Proxy.NO_PROXY).addInterceptor(interceptor).readTimeout(50, TimeUnit.SECONDS).writeTimeout(50, TimeUnit.SECONDS).connectTimeout(15, TimeUnit.SECONDS).build();
            }
        }
        return okHttpClient;
    }

    public <T> T getApi(Class<T> api) {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BuildConfig.BASE_URL)
                .addConverterFactory(stringConverteFactory)
                .addCallAdapterFactory(rxJavaCallAdapterFactory)
                .client(okHttpClient)
                .build();
        return retrofit.create(api);
    }

    /**
     * 在这里可以对网络进行拦截，进行统一处理（例如增加header,数据验签）
     * 作者：尹松涛
     * 邮箱：yinsongtaoshmily@outlook.com
     * 日期：2017/9/26
     * 时间：10:55
     */

    private class MyInterceptor implements Interceptor {

        @Override
        public Response intercept(Chain chain) throws IOException {
            Request.Builder newBuilder = chain.request().newBuilder();
            String token = "guest";
            newBuilder.addHeader("Version", String.valueOf(BuildConfig.VERSION_CODE));
            newBuilder.addHeader("Token", token);

            Request newRequest = newBuilder.build();

            StringBuilder builder = new StringBuilder();
            builder.append("-----------[ ").append(newRequest.url()).append("] request-----------").append("\r\n");
            builder.append("token->").append(token).append("\r\n");
            LogUtils.e("okHttp", builder.toString());

            Response response = chain.proceed(newRequest);
            ResponseBody responseBody = response.body();
            BufferedSource source = responseBody.source();
            source.request(Long.MAX_VALUE);
            Buffer buffer = source.buffer();
            Charset charset = UTF8;
            MediaType contentType = responseBody.contentType();
            if (contentType != null) {
                charset = contentType.charset(UTF8);
            }
            String str = buffer.clone().readString(charset);
            builder.delete(0, builder.length() - 1);
            builder.append("-----------[ ").append(newRequest.url()).append("] reponse-----------").append("\r\n");
            builder.append("response->").append(str);
            LogUtils.e("okHttp", builder.toString());
            return response;
        }

    }
}